package com.katze.ssh;

import org.apache.sshd.common.AttributeRepository;
import org.apache.sshd.common.session.Session;
import org.apache.sshd.common.session.SessionListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

public class DefaultSessionListener implements SessionListener {
    private static final Logger log = LoggerFactory.getLogger(DefaultSessionListener.class);
    public static final AttributeRepository.AttributeKey<String> KEY = new AttributeRepository.AttributeKey<>();
    private final Map<String, SshSessionKey> maps = new ConcurrentHashMap<>();

    @Override
    public void sessionCreated(Session session) {
        String key = session.getAttribute(KEY);
        log.info("{}会话创建: {}", key,session);
    }

    @Override
    public void sessionEvent(Session session, Event event) {
        String key = session.getAttribute(KEY);
        log.debug("{}会话事件: {}", key, event);
    }


    @Override
    public void sessionClosed(Session session) {
        String key = session.getAttribute(KEY);
        maps.remove(key);
        log.info("{}会话已关闭: {}, 当前会话量: {}", key, session, maps.size());
    }

    public <T>T sessionConfig(Function<Map<String, SshSessionKey>, T> action) {
        return action.apply(maps);
    }
}
